package websocket;

import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.util.Date;

/**
 * @Author: admin
 * @Description:
 * @Date: 2018/7/23 9:32
 */

public class WebSocket extends WebSocketServer {

    public WebSocket(int port) {
        super(new InetSocketAddress(port));
    }

    public WebSocket(InetSocketAddress address) {
        super(address);
    }

    public void onOpen(org.java_websocket.WebSocket webSocket, ClientHandshake clientHandshake) {
        System.out.println("open: "+webSocket.toString());
    }

    public void onClose(org.java_websocket.WebSocket webSocket, int i, String s, boolean b) {
        System.out.println("close: ");
    }

    public void onMessage(org.java_websocket.WebSocket webSocket, String s) {
        System.out.println(webSocket.toString()+" message: "+s);
        long time=new Date().getTime();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    webSocket.send("hello world: "+ time);}
            }
        }).start();

    }

    public void onError(org.java_websocket.WebSocket webSocket, Exception e) {
        System.out.println("error: "+e.getMessage());
    }
}
